<template>
  <div>
    <!-- 搜索条件 -->
    <el-card v-show="showQueryForm" class="form-card">
      <QueryForm ref="queryFormRef" :form-data="queryFormData" :items="queryFormItems" :model="queryFormData" :show-control="true" label-width="82px">

        <QueryFormItem label="申请时间" :col-multiple="1.5">
          <el-date-picker v-model="pickerDate"
                          :shortcuts="pickerShortcuts"
                          class="card-header-extra-action"
                          clearable
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD"
                          start-placeholder="开始日期"
                          type="daterange"
                          value-format="YYYY-MM-DD"/>
        </QueryFormItem>

        <template #control>
          <el-button icon="Search" type="info" @click="handleSearch">{{ $t('form.search') }}</el-button>
          <el-button icon="Refresh" @click="handleResetQueryForm">{{ $t('form.reset') }}</el-button>
        </template>
      </QueryForm>
    </el-card>

    <!-- 统计信息 -->
    <el-row class="panel-group" :gutter="8">
      <el-col :md="8" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.amount"
                    icon-class="money"
                    icon-style="style1"
                    panel-text="提现申请总额">
        </card-panel>
      </el-col>

      <el-col :md="8" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.actual_amount"
                    icon-class="rose"
                    icon-style="style2"
                    panel-text="实际到账总额">
        </card-panel>
      </el-col>

      <el-col :md="8" :sm="12" class="card-panel-col">
        <card-panel :decimals="2"
                    :model-value="statisticsData.poundage_fee"
                    icon-class="ribbon"
                    icon-style="style3"
                    panel-text="手续费总额">
        </card-panel>
      </el-col>
    </el-row>

    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:show-query-form="showQueryForm"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">

            <template #user_id="scope">
              <span>{{ scope.row.account }}</span>
              /
              <UserInfoLink :user-id="scope.row.user_id"/>
            </template>

            <template #type="scope">
              <DictTag v-model="scope.row.type" :circle="false" dict-type="withdraw_type"/>
            </template>

            <template #status="scope">
              <DictTag v-model="scope.row.status" :circle="false" dict-type="withdraw_status"/>
            </template>

            <template #account_type="scope">
              <DictTag v-model="scope.row.account_type" :circle="false" dict-type="withdraw_account_type"/>
            </template>

            <template #operations="scope">
              <!-- 查看订单信息 -->
              <el-button v-permission="'withdraw:record:info'" link type="info" @click="handleShowInfo(scope.row.id)">详情</el-button>
              <!-- 处理状态 10:处理中 20:打款中 100:打款成功 110:已驳回 120:已失败 -->
              <template v-if="hasPermission('withdraw:record:audit')">
                <el-button v-if="scope.row.status === 10" link type="primary" @click="handleAudit(scope.row,1)">通过</el-button>
                <el-button v-if="scope.row.status === 10" link type="danger" @click="handleAudit(scope.row,0)">驳回</el-button>
                <!--                <el-button v-if="scope.row.status === 20" link type="primary" @click="handleAfterSalesVerify(scope.row)">验证</el-button>-->
              </template>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

    <InfoDrawer ref="infoRef" @audit="handleAudit"/>
  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, reactive, ref } from 'vue';
import { QueryForm, QueryFormItem } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElLoading, ElMessage, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth, pickerShortcuts, toDecimal } from '@/utils';
import { QueryFormItemRule } from '@/components/query-form/constants.ts';
import { DictTag } from '@/components/dict-tag';
import { UserInfoLink } from '@/components/user-info-link';
import InfoDrawer from './info-drawer.vue';
import { WithdrawRecord, withdrawRecordAudit, withdrawRecordList } from '@/api/api-finance.ts';
import { CardPanel } from '@/components/other';

defineOptions({name: 'withdraw-record-list'});

// 查询
const queryFormData = reactive({
  type: undefined,
  status: undefined,
  user_id: undefined,
  account: undefined,
  // 时间范围 格式 2023-01-01~2023-01-31
  date: undefined,
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();
const queryFormItems = ref<QueryFormItemRule[]>([
  {type: 'dict-select', prop: 'type', label: '提现类型', placeholder: '请选择提现类型', dictType: 'withdraw_type', clearable: true,},
  {type: 'dict-select', prop: 'status', label: '提现状态', placeholder: '请选择提现状态', dictType: 'withdraw_status', clearable: true,},
  {type: 'input', prop: 'user_id', label: '用户编号', placeholder: '请输入用户编号', clearable: true,},
  {type: 'input', prop: 'account', label: '用户账号', placeholder: '请输入用户账号', clearable: true,},
]);

const statisticsData = reactive({
  amount: 0,
  actual_amount: 0,
  poundage_fee: 0
});

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<WithdrawRecord[]>([]);
const totalCount = ref(0);
const pickerDate = ref([]);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('withdraw:record:info')) count += 1
  if (hasPermission('withdraw:record:audit')) count += 2
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {prop: 'id', label: '编号', width: 105, align: 'center', sortable: 'custom'},
  {prop: 'type', label: '类型', minWidth: 130, align: 'right', headerAlign: 'center', sortable: 'custom'},
  {prop: 'user_id', label: '申请人', minWidth: 160, align: 'center', sortable: 'custom'},
  {prop: 'amount', label: '申请数量', minWidth: 120, align: 'right', headerAlign: 'center', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 2) || '-'}</span>},
  {prop: 'actual_amount', label: '实际到账', minWidth: 120, align: 'right', headerAlign: 'center', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 2) || '-'}</span>},
  {prop: 'poundage_fee', label: '手续费', minWidth: 120, align: 'right', headerAlign: 'center', sortable: 'custom', render: (scope, val) => <span>{val > 0 ? toDecimal(val, 2) : '-'}</span>},
  {prop: 'status', label: '提现状态', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'create_time', label: '申请时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'account_type', label: '账户类型', minWidth: 120, align: 'center', sortable: 'custom'},
  {prop: 'alipay_name', label: '支付宝姓名', width: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'alipay_account', label: '支付宝账号', width: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'holder', label: '持卡人', width: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'card_no', label: '银行卡号', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'bank_name', label: '开户银行', width: 160, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'audit_time', label: '审核时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'audit_reason', label: '审核描述', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
  {prop: 'update_time', label: '更新时间', width: 180, align: 'center', sortable: 'custom', render: (scope, val) => <span>{val || '-'}</span>},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'left', headerAlign: 'center'},)
  }
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 时间范围参数
    // @ts-ignore
    queryFormData.date = pickerDate.value && pickerDate.value.length == 2 ? pickerDate.value[0] + '~' + pickerDate.value[1] : undefined
    // 查询数据
    const {data} = await withdrawRecordList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      ...queryFormData,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
    // 设置数据
    statisticsData.amount = data.statistics.amount;
    statisticsData.actual_amount = data.statistics.actual_amount;
    statisticsData.poundage_fee = data.statistics.poundage_fee;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  pickerDate.value = [];
  clearSelection();
  handleResetForm();
};

/** 添加/修改操作 */
const infoRef = ref();
const handleShowInfo = (id: number) => {
  infoRef.value?.open(id);
};

/** 审核操作 */
const handleAudit = (row: any, status: number) => {
  ElMessageBox.prompt(h('p', null, ['是否确认对记录进行 ', h('span', {style: 'font-weight: bold'}, status === 1 ? '通过' : '驳回'), ' 操作吗 ？',]), {
    title: '提示',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: status === 1 ? '通过' : '驳回',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入操作原因',
  }).then(({value}) => {
    if (value == null || value.length <= 0) {
      ElMessage.error('请输入操作原因')
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    let params = {
      id: row.id,
      status: status,
      reason: value
    }
    // 提交数据
    withdrawRecordAudit(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '已提交至队列中', type: 'success', duration: 2000})
      // 刷新列表数据
      handleSearch();
    }).finally(() => loading.close())
  });
};
</script>

<style lang="scss" scoped>

</style>
